#include "queue_network.h"

// Node 构造函数
Node::Node(const QString& name, double serviceRate)
    : name(name), serviceRate(serviceRate), arrivalRate(0.0), queueLength(0.0) {}


// QueueNetwork 构造函数
QueueNetwork::QueueNetwork(const QVector<QVector<double>>& interestMatrix, const QVector<QString>& locations,double initarrivalrate)
    : interestMatrix(interestMatrix) {
    for (const auto& location : locations) {
        nodes.append(Node(location, 1.0));  // 假设每个景点的服务率初始值为1.0
    }

    // 假设第一个节点为主要入口，设置初始到达率
    if (!nodes.isEmpty()) {

        nodes[locations.length()-1].arrivalRate = initarrivalrate;  // 设置初始到达率
    }
}

// 归一化兴趣矩阵
QVector<QVector<double>> QueueNetwork::normalizeInterestMatrix(const QVector<QVector<double>>& matrix) {
    QVector<QVector<double>> normalizedMatrix(matrix.size(), QVector<double>(matrix.size(), 0.0));

    for (int i = 0; i < matrix.size(); ++i) {
        double rowSum = 0.0;

        // 将距离转换为兴趣值（取距离的倒数）
        for (int j = 0; j < matrix[i].size(); ++j) {
            if (i != j && matrix[i][j] > 0) {
                double interest = 1.0 / (matrix[i][j] + 0.0001); // 加上一个小数避免除以零
                normalizedMatrix[i][j] = interest;
                rowSum += interest;
            }
        }

        // 归一化处理
        if (rowSum > 0) {
            for (int j = 0; j < matrix[i].size(); ++j) {
                if (i != j && matrix[i][j] > 0) {
                    normalizedMatrix[i][j] /= rowSum;
                }
            }
        }
    }

    return normalizedMatrix;
}

// 计算到达率
void QueueNetwork::calculateTraffic() {
    QVector<QVector<double>> normalizedMatrix = normalizeInterestMatrix(interestMatrix);
    QVector<double> newArrivalRates(nodes.size(), 0.0);  // 临时存储新的到达率

    for (int iter = 0; iter < 100; ++iter) {  // 最大迭代次数，防止死循环
        for (int i = 0; i < nodes.size(); ++i) {
            double arrivalRate = 0.0;
            for (int j = 0; j < nodes.size(); ++j) {
                if (i != j) {
                    arrivalRate += nodes[j].arrivalRate * normalizedMatrix[j][i];
                }
            }
            newArrivalRates[i] = arrivalRate;
        }
        // 更新所有节点的到达率
        for (int i = 0; i < nodes.size(); ++i) {
            nodes[i].arrivalRate = newArrivalRates[i];
        }
    }
}

// 计算队列长度等指标
void QueueNetwork::calculateQueueMetrics() {
    for (auto& node : nodes) {
        if (node.serviceRate > node.arrivalRate) {
            node.queueLength = node.arrivalRate / (node.serviceRate - node.arrivalRate)*5;
        } else {
            node.queueLength = -1;  // 表示队列溢出或不可达状态
        }
    }
}

// 显示结果
void QueueNetwork::displayResults() {
    for (const auto& node : nodes) {
        qDebug() << "景点:" << node.name << ", 到达率:" << node.arrivalRate << ", 队列长度:" << node.queueLength;
    }
}

QVector<double> QueueNetwork::returnLength(){
    QVector<double> Length;
    for (const auto& node : nodes) {
        Length.append(node.queueLength);
    }
    return Length;
}

